package com.spsoft.vms.redis.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.spsoft.vms.redis.constant.RedisConstant;
import com.spsoft.vms.redis.service.VmsQueueService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 查询上传发票结果延时队列
 * 上传发票后，把查询的号码放入延时队列，等待一定时间后，查询结果
 * @author cdl
 * @date 2024/03/13
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class QueryUploadInvoiceVmsQueueServiceImpl implements VmsQueueService<String> {

    private final RedissonClient redisson;

    /**
     * message的格式为：受理流水号-机构编码-重试次数
     * 例如：lsh1710407198123-1010-0
     * 1.获取延迟队列
     * 2.随机生成10-300s延迟时间
     * 3.将message添加到延迟队列中
     */
    @Override
    public boolean addMessageToQueue(String message) {
        try {
            String[] split = message.split("-");
            if (split.length != 3) {
                log.error("message：{}，数据格式错误", message);
                return false;
            }
            int i = RandomUtil.randomInt(10, 300);
            RBlockingQueue<String> blockingQueue = redisson.getBlockingQueue(RedisConstant.QUEUE_INVOICE_DELAY_QUERY_UPLOAD);
            RDelayedQueue<String> delayedQueue = redisson.getDelayedQueue(blockingQueue);
            delayedQueue.offer(message, i, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            log.error("添加：{}到延时队列失败:{}", message, e.getMessage());
            return false;
        }
    }

    @Override
    public String getMessageFromQueue() {
        RBlockingQueue<String> blockingQueue = redisson.getBlockingQueue(RedisConstant.QUEUE_INVOICE_DELAY_QUERY_UPLOAD);
        return blockingQueue.poll();
    }

    @Override
    public List<String> getMessagesFromQueue(int count) {
        RBlockingQueue<String> blockingQueue = redisson.getBlockingQueue(RedisConstant.QUEUE_INVOICE_DELAY_QUERY_UPLOAD);
        return blockingQueue.poll(count);
    }

    @Override
    public int getQueueSize() {
        RBlockingQueue<String> blockingQueue = redisson.getBlockingQueue(RedisConstant.QUEUE_INVOICE_DELAY_QUERY_UPLOAD);
        return blockingQueue.size();
    }

    @Override
    public boolean containsMessage(String message) {
        RBlockingQueue<String> blockingQueue = redisson.getBlockingQueue(RedisConstant.QUEUE_INVOICE_DELAY_QUERY_UPLOAD);
        return blockingQueue.contains(message);
    }
}
